import 'dart:math';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/vip/vip_logic.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/entity/vip/vip_pay_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/pick/items/avator_label.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/path.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../utils/user.dart';
import '../../widgets/base/qkd_text.dart';
import '../home/qkd_carousel_view.dart';

class VipPage extends StatefulWidget {
  const VipPage({super.key, this.showAppBar = true});

  final bool showAppBar;
  @override
  State<VipPage> createState() => _VipPageState();
}

class _VipPageState extends State<VipPage> with AutomaticKeepAliveClientMixin {
  late final VipLogic logic;
  var tag = Random().nextDouble() * 10000;
  late final double topPadding =
      (widget.showAppBar ? 132 : MediaQuery.of(context).padding.top + 122);

  @override
  void initState() {
    logic = Get.put(VipLogic(),
        tag: "${widget.showAppBar}${widget.showAppBar ? tag : ""}");
    logic.scrollController.addListener(() {
      if (logic.num <= 1) {
        logic.num = logic.scrollController.offset / topPadding;
      }
    });
    logic.getBack(!widget.showAppBar);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<VipLogic>(
        tag: "${widget.showAppBar}${widget.showAppBar ? tag : ""}",
        builder: (logic) {
          return VisibilityDetector(
            key: const Key("vip"),
            onVisibilityChanged: (VisibilityInfo info) => update(),
            child: Scaffold(
                backgroundColor: widget.showAppBar
                    ? Colours.greyF2F3F7
                    : Colours.transparent,
                extendBodyBehindAppBar: true,
                appBar: Styles.appBar(
                    showLeading: widget.showAppBar,
                    backgroundColor: Colours.transparent,
                    title: QkdText(widget.showAppBar ? "会员中心" : "")),
                body: Stack(
                  children: [
                    if (widget.showAppBar)
                      Positioned(
                        left: 0,
                        right: 0,
                        top: 0,
                        child: QkdCarouselView(
                          carousels: logic.carousel,
                          aspectRatio: 375 / 260,
                          radius: 0,
                          padding: 0,
                          dotBottom: 20,
                          needTitle: false,
                          needDot: logic.carousel.length != 1,
                        ),
                      ),
                    Positioned.fill(
                        child: SafeArea(
                      top: widget.showAppBar,
                      child: Obx(() => Container(
                            color: Colours.greyF2F3F7.withOpacity(logic.num),
                          )),
                    )),
                    SafeArea(
                      top: widget.showAppBar,
                      child: EasyRefresh.builder(
                        controller: logic.refreshController,
                        scrollController: logic.scrollController,
                        header: Styles.refreshHeader(
                            position: IndicatorPosition.locator,
                            backgroundColor: Colours.greyF2F3F7),
                        onRefresh: logic.getData,
                        childBuilder:
                            (BuildContext context, ScrollPhysics physics) =>
                                MediaQuery.removePadding(
                          removeTop: true,
                          context: context,
                          child: ListView(
                            physics: physics,
                            controller: logic.scrollController,
                            children: [
                              if (widget.showAppBar)
                                Container(height: topPadding),
                              const HeaderLocator(),
                              if (!widget.showAppBar)
                                QkdCarouselView(
                                  carousels: logic.carousel,
                                  aspectRatio: 359 / 120,
                                  radius: 8,
                                  padding: 8,
                                  needTitle: false,
                                  needDot: logic.carousel.length != 1,
                                ).paddingSymmetric(vertical: 8),
                              userInfo(),
                              if (logic.benefit.hasValue) benefit(),
                              if (logic.plan.hasValue) ...freePlan(),
                              if (logic.discount.hasValue) ...discount(),
                              if (logic.right.hasValue) ...right(),
                              Container(height: 70)
                            ],
                          ),
                        ),
                      ),
                    ),
                    Positioned(bottom: 16, left: 0, right: 0, child: payBar())
                  ],
                )),
          );
        });
  }

  Widget userInfo() {
    return Block(
      cardStyle: logic.style,
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: AvatarLabel.normal(
                    avatarSize: 52,
                    avatarUrl: User.info?.avatar ?? "",
                    name: User.isLogin ? (User.info?.name ?? "") : "登录/注册",
                    id: User.info?.id,
                    nameSize: 16,
                    nameWeight: FontWeight.w500,
                    content: User.isLogin && User.info?.isVip == 1
                        ? "${DateTime.tryParse(User.info?.vipEndTime ?? "")?.formatedString("yyyy-MM-dd")} 到期"
                        : "开通会员，畅享权益",
                    contentStyle:
                        const TextStyle(fontSize: 12, color: Colours.grey66),
                    needJump: () {
                      if (!User.isLogin) {
                        User.needLogin(() =>
                            User.fetchUserInfo().then((value) => update()));
                      }
                    }),
              ),
              goldButton(onTap: () {
                Utils.onEvent("syhy", params: {"syhy": "0"});
                User.needLogin(logic.toPay);
              })
            ],
          ),
          Container(height: 16),
          LoadingWidget<bool>(
            isLoading: logic.price == null,
            data: logic.price?.prices?.length == 0,
            child: () => Row(
                children: List<Widget>.generate(
                        logic.price?.prices?.length ?? 0,
                        (index) => Expanded(child: priceItem(index)))
                    .insertEvery(Container(width: 8))),
          )
        ],
      ),
    );
  }

  List<Widget> discount() =>
      logic.discount.map((e) => discountItem(e)).toList();

  List<Widget> right() => logic.right.map((e) => rightItem(e)).toList();

  List<Widget> freePlan() => logic.plan.map((e) => planItem(e)).toList();

  Widget benefit() {
    return Block(
      cardStyle: logic.style,
      child: Column(children: [
        QkdText("专属权益",
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colours.gold6A3313)
            .paddingOnly(bottom: 16),
        ...logic.benefit.map((e) => benefitItem(e))
      ]),
    );
  }

  Widget rightItem(ResourceEntity e) {
    return Block(
      cardStyle: logic.style.copyWith(padding: EdgeInsets.zero),
      child: Stack(
        children: [
          if (e.imgUrl.hasValue)
            Positioned.fill(
              child: CachedNetworkImage(
                fit: BoxFit.fill,
                imageUrl: e.imgUrl!,
                errorWidget: (context, url, error) => Container(),
                placeholder: (context, url) => Container(color: Colours.white),
              ),
            ),
          Block(
            cardStyle: logic.style
                .copyWith(margin: EdgeInsets.zero, color: Colours.transparent),
            child: Column(
              children: [
                QkdText(e.title ?? "",
                    fontSize: 16, color: Colours.brown6A3313),
                Container(height: 2),
                QkdText(e.content ?? "",
                    fontSize: 12, color: Colours.goldD6A864),
                Container(height: 16),
                vipButton(
                    ((e.extInfo?.split('\n').length ?? 0) <= 1
                            ? e.extInfo
                            : e.extInfo?.split('\n')[User.info?.isVip ?? 0]) ??
                        "", onTap: () {
                  if (!User.isLogin)
                    User.needLogin(() async => await User.fetchUserInfo());
                  if (User.info?.isVip == 1) {
                    if (e.href.hasValue) {
                      if (e.href!.contains("{")) {
                        if (e.href!.contains("recharge"))
                          Utils.onEvent("syhy", params: {"syhy": "4"});
                        if (e.href!.contains("editName"))
                          Utils.onEvent("syhy", params: {"syhy": "6"});
                        Utils.doJump(e.href!);
                      } else {
                        Utils.onEvent("syhy", params: {"syhy": "5"});
                        Clipboard.setData(ClipboardData(text: e.href!));
                        ToastUtils.show("复制成功");
                      }
                    }
                  }
                })
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget discountItem(ResourceEntity e) {
    return Block(
      cardStyle: logic.style,
      child: Column(
        children: [
          QkdText(e.title ?? "", fontSize: 16, color: Colours.brown6A3313),
          Container(height: 2),
          QkdText(e.content ?? "", fontSize: 12, color: Colours.goldD6A864),
          Container(height: 16),
          if (e.imgUrl.hasValue)
            CachedNetworkImage(
                fit: BoxFit.fitWidth,
                imageUrl: e.imgUrl!,
                errorWidget: (context, url, error) => Container()),
          if (e.imgUrl.hasValue) Container(height: 16),
          vipButton(
              ((e.extInfo?.split('\n').length ?? 0) <= 1
                      ? e.extInfo
                      : e.extInfo?.split('\n')[User.info?.isVip ?? 0]) ??
                  "", onTap: () {
            if (User.info?.isVip == 1) {
              if (e.href.hasValue) {
                if (e.href!.contains("{")) {
                  if (e.href!.contains("ai"))
                    Utils.onEvent("syhy", params: {"syhy": "3"});
                  if (e.href!.contains("home"))
                    Utils.onEvent("syhy", params: {"syhy": "2"});
                  Utils.doJump(e.href!);
                }
              }
            }
          })
        ],
      ),
    );
  }

  Widget priceItem(int index) {
    VipPrices price = logic.price!.prices![index];
    return GestureDetector(
      onTap: () => logic.index = index,
      child: Container(
        height: 108,
        decoration: BoxDecoration(
            color: index == logic.index ? Colours.goldFBF7EF : Colours.white,
            border: Border.all(
                color:
                    index == logic.index ? Colours.goldD6A864 : Colours.greyEE,
                width: 1,
                strokeAlign: BorderSide.strokeAlignOutside),
            borderRadius: BorderRadius.circular(8)),
        child: DefaultTextStyle(
          style: const TextStyle(color: Colours.goldD6A864),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              QkdText(price.name ?? "",
                  fontSize: 16, fontWeight: FontWeight.w500),
              Text.rich(TextSpan(
                  style: const TextStyle(color: Colours.text, fontSize: 23),
                  children: [
                    TextSpan(
                        text: price.price?.split("球币").join() ?? "",
                        style: const TextStyle(
                            fontWeight: FontWeight.w600,
                            fontFamily: "Din",
                            letterSpacing: -2)),
                    TextSpan(
                        text: "球币".changeUnit,
                        style: const TextStyle(
                            fontSize: 12, fontWeight: FontWeight.w500)),
                  ])),
              if (price.priceOld.hasValue)
                QkdText("${price.priceOld!}球币".changeUnit, fontSize: 12)
            ],
          ),
        ),
      ),
    );
  }

  Widget planItem(ResourceEntity e) {
    return Block(
      cardStyle: logic.style.copyWith(backImg: "vip_plan_back.png"),
      child: Column(
        children: [
          QkdText(e.title ?? "", fontSize: 16, color: Colours.brown6A3313),
          Container(height: 2),
          QkdText(e.content ?? "", fontSize: 12, color: Colours.goldD6A864),
          Container(height: 32),
          vipButton(
              ((e.extInfo?.split('\n').length ?? 0) <= 1
                      ? e.extInfo
                      : e.extInfo?.split('\n')[User.info?.isVip ?? 0]) ??
                  "", onTap: () {
            Utils.onEvent("syhy", params: {"syhy": "1"});
            // User.needLogin(() async=> await User.fetchUserInfos());
            if (e.href != null) {
              if (e.href!.contains("{")) {
                Utils.doJump(e.href!);
              }
            }
          }),
          Container(height: 40)
        ],
      ),
    );
  }

  Widget benefitItem(ResourceEntity e) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 20),
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
          color: Colours.greyF7F9FB,
          border: Border.all(
              color: Colours.goldD6A864,
              width: 0.5,
              strokeAlign: BorderSide.strokeAlignOutside),
          borderRadius: BorderRadius.circular(8)),
      child: Row(
        children: [
          Expanded(
              child: AvatarLabel.normal(
            nameSize: 16,
            nameWeight: FontWeight.w500,
            avatarUrl: e.imgUrl,
            name: e.title,
            id: "",
            needJump: () {},
            content: e.content,
            contentStyle: const TextStyle(fontSize: 12, color: Colours.grey66),
          )),
          goldButton(
              buttonText: ((e.extInfo?.split('\n').length ?? 0) <= 1
                      ? e.extInfo
                      : e.extInfo?.split('\n')[User.info?.isVip ?? 0]) ??
                  "",
              onTap: () {
                if (User.info?.isVip == 1) {
                  if (e.href != null) {
                    if (!User.isLogin)
                      User.needLogin(() async => await User.fetchUserInfo());
                    if (e.href!.contains("{")) {
                      Utils.doJump(e.href!);
                    }
                  }
                }
              },
              width: 72)
        ],
      ),
    );
  }

  Widget goldButton({String? buttonText, Function()? onTap, double? width}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: width ?? 84,
        height: 29,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            gradient: const LinearGradient(
              colors: [Colours.goldF6E0BE, Colours.goldE0BE84],
            ),
            borderRadius: BorderRadius.circular(22)),
        child: QkdText(
            buttonText ?? "立即${logic.price?.open == true ? "续费" : "开通"}",
            needCenter: true,
            fontSize: 12,
            fontWeight: FontWeight.w500,
            color: Colours.brown624118),
      ),
    );
  }

  Widget vipButton(String title, {Function()? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 122,
        height: 32,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colours.grey3E3A3A, borderRadius: BorderRadius.circular(35)),
        child: QkdText(title,
            needCenter: true, fontSize: 12, color: Colours.goldFFF0CA),
      ),
    );
  }

  Widget payBar() {
    VipPrices? price = logic.price?.prices?[logic.index];
    return Column(
      children: [
        Stack(
          children: [
            Container(
              height: 48,
              margin: const EdgeInsets.symmetric(horizontal: 12),
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(24),
                  gradient: const LinearGradient(
                      colors: [Color(0xFF6A6967), Color(0xFF413D3D)],
                      stops: [0, 0.4])),
              child: Stack(
                children: [
                  Row(
                    children: [
                      if (price?.price != null)
                        QkdText(
                            price?.price == "0球币"
                                ? "限时免费"
                                : "${price?.price ?? ""}/${price?.name?.split("包").join() ?? ""}",
                            fontSize: 16,
                            color: Colours.white,
                            fontWeight: FontWeight.w500),
                      Container(width: 4),
                      // if (price?.priceOld != null && price?.priceOld != price?.price)
                      //   QkdText("${price?.priceOld ?? ""}/${price?.name?.split("包").join() ?? ""}",
                      //     strutStyle: Styles.centerStyle(fontSize: 12),
                      //     style: const TextStyle(
                      //       fontSize: 12,
                      //       decoration: TextDecoration.lineThrough,
                      //       color: Colours.grey99)),
                    ],
                  ).paddingSymmetric(horizontal: 16),
                  Positioned(
                    top: 0,
                    bottom: 0,
                    right: 0,
                    child: ClipPath(
                      clipper: TrapezoidPath(false),
                      child: GestureDetector(
                        onTap: () {
                          Utils.onEvent("syhy", params: {"syhy": "0"});
                          User.needLogin(logic.toPay);
                        },
                        child: Container(
                            width: 132,
                            alignment: Alignment.center,
                            decoration: const BoxDecoration(
                                gradient: LinearGradient(colors: [
                              Color(0xFFF5E0BE),
                              Color(0xFFE1BF84)
                            ])),
                            child: QkdText(
                                "立即${logic.price?.open == true ? "续费" : "开通"}",
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                                color: Colours.brown6A3313)),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
        Container(
            color: Colours.white, height: MediaQuery.of(context).padding.bottom)
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
